$(function () {
  init()

  account.forceLogin = false
  account.getUserInfo((err, userInfo) => {
    if (!err) {
      if (userInfo && userInfo.shareFlag) window.activeShare(userInfo.shareFlag)
      window.userInfo = userInfo
      console.log(userInfo)
      getGroupBuyInfo()
    } else {
      window.location.href = `${campUrl}${Math.ceil(Math.random() * 100)}?_c=${campaign}&_gid=${gid}`
    }
  })
  getGroupBuyInfo()

  function getGroupBuyInfo () {
    account.ajax($.extend({
      type: 'POST',
      path: `/s/products/${campaignProduct}/buying`,
      success: result => {
        console.log(result)
        // //已经开团
        resetShareDetail(result.id)
        window.creator = result.creatorId
        window.winningUserId = result.winningUserId
        getGroupBuyerList(result.buyers.toString())
      },
      error: err => window.location.href = window.campUrl
    }, !gid ? {} : {
      auth: false,
      data: {groupBuyingId: encodeURIComponent(decodeURIComponent(gid))}
    }))
  }

  function getGroupBuyerList (ids) {
    account.ajax({
      auth: false,
      type: 'GET',
      path: '/s/students/socials',
      data: {ids},
      success: setUserList,
      error: err => utils.toastAlert(err.message)
    })
  }

  // 显示分享
  $('.share-btn').off('click').on('click', e => {
    $('.share-mask').show()
  })

  // 隐藏分享
  $('.share-mask').off('click').on('click', e => {
    $('.share-mask').hide()
  })

  function setUserList (userList) {
    console.log(userList)
    $('.user-list').empty()
    const defaultAvatar = `${CDN_RESOURCE}/mobile/campaign/lottery/img/default.png`
    const nullAvatar = `${CDN_RESOURCE}/mobile/campaign/lottery/img/avatar.png`
    userList.sort(user => user.id === creator ? -1 : 1)
    const winner = userList.find(user => user.id === winningUserId)
    if (userInfo.id === winningUserId) {
      $('.title-1').html(`恭喜您手气最佳，获得价值<span class="red">￥120</span>/3课时<br/>`)
      $('.title-2').html(`其余7人获得1课时`)
    } else {
      $('.title-1').html(`恭喜您获得价值<span class="red">￥40</span>/1节北美外教课!`)
      $('.title-2').html(`本团${winner.nickname}手气最佳，获得￥120/3课时`)
    }
    for (let i = 0; i < 8; i++) {
      const user = i < userList.length ? userList[i] : false
      const captain = i === 0 ? 'captain' : ''
      const win = user && user.id === winningUserId ? 'win' : ''
      const avatar = user ? (user.avatar ? user.avatar : nullAvatar) : defaultAvatar
      $('.user-list').append(`
        <div class="user-item ${captain} ${win}">
          <img class="avatar" src="${avatar}" onerror="this.src='${defaultAvatar}'">
        </div>
      `)
    }
  }

  function resetShareDetail (_gid) {
    window.gid = _gid
    window.localStorage.setItem('lottery_gid', gid)
    console.log(`reset_gid=${gid}`)
    account.getUserInfo((err, result) => {
      if (!err && utils.isWeChat()) window.activeShare(result.shareFlag)
    })
  }
})

function init () {
  window.campaign = 'lottery'
  window.avPrefix = 'p008'
  window.campUrl = `${window.location.protocol}//${window.location.host}/wx/${campaign}`
  window.analytics = AV.analytics({
    appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
    appKey: 'jqyWxLyobpsmdwsJddJlDheb',
    channel: utils.isWeChat() ? 'weixin' : ''
  })
  getGId()
  window.wxconfig = new WxConfig(wechatConfig, campaign)
  window.account = new Account()
  setShare()
  getChannel()
  analytics.send({
    event: `${avPrefix}_result_open`,
    attr: {gid}
  })
}

function getGId () {
  let state = utils.getUrlParam('state') || ''
  let gid = utils.getUrlParam('_gid') || utils.getUrlParam('gid') || state.replace('gid_', '')
  console.log(`gid=${gid}`)
  window.gid = gid
  return gid
}

function getChannel () {
  if (!utils.getUrlParam('_c')) {
    const QKidsChannel = JSON.parse(window.localStorage.getItem('QKidsChannel'))
    if (!(QKidsChannel && QKidsChannel.expires > new Date().getTime() / 1000)) {
      window.localStorage.setItem('QKidsChannel', JSON.stringify({
        rawData: `${campaign}_share`,
        expires: new Date().getTime() / 1000 + 24 * 3600
      }))
    }
  }
}

function setShare () {
  window.shareFlag = ''
  window.shareMsg = shareFlag => {
    return {
      title: '【久趣福利】1元抢3节北美外教课！',
      desc: '100%北美外教在线教学，让孩子爱上英语！',
      link: `${campUrl}${Math.ceil(Math.random() * 100)}?_c=${campaign}&_r=${shareFlag}&_gid=${gid}`,
      imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
      success: target => {
        analytics.send({
          event: `${avPrefix}_share_success`,
          attr: {target}
        })
      }
    }
  }
  window.activeShare = shareFlag => {
    console.log(shareMsg(shareFlag))
    if (utils.isWeChat()) window.shareFlag = shareFlag || ''
    wxconfig.activeShare(shareFlag, '', shareMsg(shareFlag))
  }
}